package com.springboot.middleware.middleware_rabbitmq_logforlogin.server.publisher;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.middleware.middleware_rabbitmq_logforlogin.server.dto.UserLoginDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * 系统日志记录-生产者
 */
@Component
public class LogPublisher {
    private static final Logger log = LoggerFactory.getLogger(LogPublisher.class);
    private static final String exchangeName = "dev.login.topic.exchange";
    private static final String queueName = "dev.login.queue";
    private static final String routingKey = "dev.login.log";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //环境变量
    @Autowired
    private Environment evn;

    //JSON序列化和反序列化组件
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 将登陆成功后的用户相关信息发送给队列
     * @param loginDto
     */
    public void sendLogMsg(UserLoginDto loginDto) {
        try {
            //设置消息传送格式-JSON
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            MessagePostProcessor args = message -> {
                //设置消息的持久化模式为持久化
                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                //设置消息头,表示传输的消息直接指定为某个类实例,消费者在监听消费时可以直接定义该类对象参数进行接受即可
                message.getMessageProperties().setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, UserLoginDto.class);
                return message;
            };
            rabbitTemplate.convertAndSend(exchangeName, routingKey, loginDto, args);
            log.info("系统日志记录-生产者-将登陆成功后的用户相关信息发送给队列-内容:{}", loginDto);
        } catch (Exception e) {
            log.error("系统日志记录-生产者-将登陆成功后的用户相关信息发送给队列-发生异常:{}", loginDto, e.fillInStackTrace());
        }
    }
}
